package lv.accenture.ex06;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexExtractor implements IExtractor {

	public List<Bookmark> extractBookmarks(String resource) throws IOException {
		List<Bookmark> result = new ArrayList<Bookmark>();
		FileResourceReader reader = new FileResourceReader();
		List<String> lines = reader.readLines(resource);

		Bookmark bm = new Bookmark();
		boolean channel = false;
		for (int i = 0; i < lines.size(); i++) {
			
			String line = lines.get(i);
			Pattern p0 = Pattern.compile("<item rdf:about=\"([^\"]+)\">");			
			Matcher m0 = p0.matcher(line);
			if (m0.matches()) {
				String url = m0.group(1); 
				//System.err.println("url = " + url);
				channel = true;
				bm.setUrl(url);
			}
			
			if (channel) {
				
				Pattern p1 = Pattern.compile("<title>([^\"]+)</title>");			
				Matcher m1 = p1.matcher(line); 
				if (m1.matches()) {
					String  title = m1.group(1);
					//System.err.println("title = " + title);
					bm.setTitle(title);
				}
				
				Pattern p2 = Pattern.compile("<description>([^\"]*)</description>");			
				Matcher m2 = p2.matcher(line); 
				if (m2.matches()) {
					String  description = m2.group(1);
					//System.err.println("description = " + description);
					bm.setDescription(description);
				}
				
				Pattern p3 = Pattern.compile("<dc:creator>([^\"]*)</dc:creator>");			
				Matcher m3 = p3.matcher(line); 
				if (m3.matches()) {
					String  creator = m3.group(1);
					//System.err.println("creator = " + creator);
					bm.setCreator(creator);
				}
				
				Pattern p4 = Pattern.compile("<dc:date>([^\"]*)</dc:date>");			
				Matcher m4 = p4.matcher(line); 
				if (m4.matches()) {
					String  date = m4.group(1);
					//System.err.println("date = " + date.substring(0, 3));
					bm.setYear(date.substring(0, 3));
				}
				
				Pattern p5 = Pattern.compile("<dc:subject>([^\"]*)</dc:subject>");			
				Matcher m5 = p5.matcher(line); 
				if (m5.matches()) {
					String[]  subject = m5.group(1).split(" ");
					//for(int j = 0; j < subject.length;++j){
					//	System.err.println("subject[" + (j + 1) + "] = " + subject[j]);
					//}
					bm.setTags(Arrays.asList(subject));
					bm.setUid(Integer.toHexString(bm.getUrl().hashCode()));
					result.add(bm);
					
					bm = new Bookmark();
				}
			}
		}
		return result;
	}
}
